class PhotosController < ApplicationController
  caches_page :index

  before_filter :get_archives, :add_nav_sections

  def index
    @photo_sets = 
      PhotoSet.get_items(PhotoSet::ITEMS_PER_PAGE, params[:page])
    @photo_sets_pages = 
      PhotoSet.get_counts(PhotoSet::ITEMS_PER_PAGE)
  end
  
  def index_by_date
    return redirect_to(:action => :index) if params[:year].blank?
    
    date_start, date_end = DateRange.parse(params[:year], params[:month], params[:day])
    
    @photo_sets =
      PhotoSet.find(
        :all,
        :conditions => {
          :created_at       => date_start .. date_end,
        },
        :limit      => PhotoSet::ITEMS_PER_PAGE,
        :offset     => (@page - 1) * PhotoSet::ITEMS_PER_PAGE,
        :order      => "created_at ASC"
      )
    
    @photo_sets_pages = 
      begin
        counts = 
          PhotoSet.count(
            :all,
            :conditions => {
              :created_at       => date_start .. date_end
            }
          )
        pages = ((counts - 1)/ PhotoSet::ITEMS_PER_PAGE) + 1
        [counts, pages]
      end
    
    render :action => "photos/index"
  end
  
  def canonical
    if !params[:canonical_name].blank?
      @photo_set =
        PhotoSet.find(
          :first,
          :conditions => {
            :canonical_name => params[:canonical_name].to_s
          })
    end
    
    redirect_to photos_url if params[:canonical_name].blank? || !@photo_set
    
    @photo_sets = 
      PhotoSet.get_items
  end
  
  private
    def get_archives
      @archive = {}
      ActiveRecord::Base.connection.execute( "
        SELECT YEAR(created_at) as year, MONTH(created_at) as month, COUNT(*) as count
        FROM photo_sets p 
        GROUP BY YEAR(created_at), MONTH(created_at);
      " ).each_hash do |result|
        year = result["year"].to_i
        month = result["month"].to_i
        count = result["count"].to_i
        @archive[year] = {"total" => 0, "months" => {}} unless @archive.has_key?(year)
        @archive[year]["total"] += count
        @archive[year]["months"][month] = count
      end
    end

    def add_nav_sections
      @nav_sections << ["archives", {:type => "photos"}]
    end
end
